{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import _tree"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def tree_to_json(tree):\n",
    "    tree_ = tree.tree_\n",
    "    feature_names = range(30)\n",
    "    feature_name = [\n",
    "        feature_names[i] if i != _tree.TREE_UNDEFINED else \"undefined!\"\n",
    "        for i in tree_.feature\n",
    "    ]\n",
    "    def recurse(node):\n",
    "        tree_json = dict()\n",
    "        if tree_.feature[node] != _tree.TREE_UNDEFINED:\n",
    "            tree_json['type'] = 'split'\n",
    "            threshold = tree_.threshold[node]\n",
    "            tree_json['threshold'] = \"{} <= {}\".format(feature_name[node], threshold)\n",
    "            tree_json['left'] = recurse(tree_.children_left[node])\n",
    "            tree_json['right'] = recurse(tree_.children_right[node])\n",
    "        else:\n",
    "            tree_json['type'] = 'leaf'\n",
    "            tree_json['value'] = tree_.value[node].tolist()\n",
    "        return tree_json\n",
    "\n",
    "    return recurse(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def forest_to_json(forest):\n",
    "    forest_json = dict()\n",
    "    forest_json['n_features'] = forest.n_features_\n",
    "    forest_json['n_classes'] = forest.n_classes_\n",
    "    forest_json['classes'] = forest.classes_.tolist()\n",
    "    forest_json['n_outputs'] = forest.n_outputs_\n",
    "    forest_json['n_estimators'] = forest.n_estimators\n",
    "    forest_json['estimators'] = [tree_to_json(estimator) for estimator in forest.estimators_]\n",
    "    return forest_json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
